package com.cucn.ingmall.cart.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.cucn.common.constant.auth.SmsConstant;
import com.cucn.common.constant.cart.CartConstant;
import com.cucn.common.to.dto.MemberResponseDTO;
import com.cucn.ingmall.cart.dto.UserInfoDTO;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 购物车请求拦截器
 * 在执行目标方法请求之前，先判断用户的登录状态，并封装传递给controller目标请求
 *
 * @author KouChaoJie
 * @since: 2022/1/14 10:54
 */
public class CartInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoDTO> threadlocal = new ThreadLocal<>();

    /**
     * 目标方法执行前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoDTO userInfoDTO = new UserInfoDTO();

        MemberResponseDTO member = (MemberResponseDTO) request.getSession().getAttribute(SmsConstant.LOGIN_USER);
        if (ObjectUtil.isNotEmpty(member)) {
            //不为空,有登录用户
            userInfoDTO.setUserId(member.getId());
        }

        //如果已经有了临时用户cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
                    //将临时用户的值传递给userinfo供客户端读取
                    userInfoDTO.setUserKeyValue(cookie.getValue());
                    //已经有了临时用户,标志位设为true
                    userInfoDTO.setTempUser(true);
                }
            }
        }

        //如果没有临时用户就创建一个临时用户
        if (StringUtils.isEmpty(userInfoDTO.getUserKeyValue())) {
            userInfoDTO.setUserKeyValue(UUID.randomUUID().toString());
        }

        threadlocal.set(userInfoDTO);

        return true;
    }

    /**
     * 目标方法执行之后,响应给客户端临时用户的cookie,设置作用域
     * 分配临时用户让浏览器保存
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoDTO userInfoDTO = threadlocal.get();

        //如果没有临时用户cookie,一定保存一个临时用户cookie
        if (!userInfoDTO.isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoDTO.getUserKeyValue());
            cookie.setDomain("koukoucoding.xn--fiqs8s");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
